//
//  TTPIictureCollectionView.m
//  TTWeibo
//
//  Created by 陶宏路 on 16/7/30.
//  Copyright © 2016年 陶路路. All rights reserved.
//
#define CELLWIDTH 80
#define MARGIN 5
#import "TTPIictureCollectionView.h"
#import "TTPictureViewCell.h"
@interface TTPIictureCollectionView ()

@property (nonatomic,strong) UICollectionViewFlowLayout * flowLayout;

@end

@implementation TTPIictureCollectionView

-(instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout{
    
    if (self = [super initWithFrame:frame collectionViewLayout:[[UICollectionViewFlowLayout alloc]init]]) {
        
        [self setUpUI];
    }
    
    return self;
}

-(void)setUpUI{
    
    self.backgroundColor = [UIColor whiteColor];
    self.dataSource = self;
    [self registerClass:[TTPictureViewCell class] forCellWithReuseIdentifier:@"cell"];
    self.flowLayout = (UICollectionViewFlowLayout*)self.collectionViewLayout;
    self.flowLayout.itemSize = CGSizeMake(CELLWIDTH, CELLWIDTH);
    self.flowLayout.minimumInteritemSpacing = MARGIN;
    self.flowLayout.minimumLineSpacing = MARGIN;
    
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.width.height.equalTo(@250);
    }];
    
}


#pragma mark 根据图片是数量设置collectionView的SIZE  重新更新约束后 刷新 [self reloadData];

-(void)setArrayModel:(NSArray *)arrayModel{
    
    _arrayModel = arrayModel;
    
    CGSize viewSize = [self getSize];
    
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
       
        make.width.equalTo(@(viewSize.width));
        make.height.equalTo(@(viewSize.height));
    }];
    
    [self reloadData];
}


#pragma mark 根据图片数量 设置collectionView 的大小

-(CGSize)getSize{
    
    NSInteger count = self.arrayModel.count;
    
    NSInteger rol = count == 4 ? 2 : count >= 3? 3 : count;
    
    NSInteger col = count == 4 ? 2 : ((count - 1) / 3) + 1;
    
    CGSize size =  CGSizeMake(rol * CELLWIDTH + (rol - 1)*MARGIN, col * CELLWIDTH + (col - 1) * MARGIN);
    
    return size;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.arrayModel.count;
    
}

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    TTPictureViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.backgroundColor = RANDOMCOLOR;
    cell.model = self.arrayModel[indexPath.row];
    return cell;
}

@end
